//
// Created by hongs on 2021/8/20.
//

#ifndef NEWCGI_COM_LIST_H
#define NEWCGI_COM_LIST_H
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdint.h>

typedef struct com_list_head{
    struct com_list_head *pre,*next;
}COM_LIST_HEAD_t;

//同时初始化前一个节点和后一个节点的地址,最当前节点的使用进行初始化,及头部指针的结果进行初始化
#define LIST_HEAD_INIT(head_ptr) { &(head_ptr),&(head_ptr)}
#define LIST_HEAD(head_ptr) COM_LIST_HEAD_t head_ptr = LIST_HEAD_INIT(head_ptr)

static inline void INIT_LIST_HEAD(COM_LIST_HEAD_t *head_ptr){
    head_ptr->next = head_ptr;
    head_ptr->pre = head_ptr;
}

static inline void __list_add(COM_LIST_HEAD_t *new,COM_LIST_HEAD_t *pre,COM_LIST_HEAD_t *next)
{
    next->pre = new;
    new->next = next;
    new->pre = pre;
    pre->next = new;
}

static inline void list_add_tail(COM_LIST_HEAD_t *new,COM_LIST_HEAD_t *head)
{
    __list_add(new,head->pre,head);
}

static inline void __list_del(COM_LIST_HEAD_t *pre,COM_LIST_HEAD_t *next){
    next->pre = pre;
    pre->next = next;
}

// 节点为即将要删除的节点进行使用
static inline void list_del(COM_LIST_HEAD_t *del_node)
{
    __list_del(del_node->pre,del_node->next);
}

static inline void list_del_init(COM_LIST_HEAD_t *del_node)
{
    list_del(del_node);
    INIT_LIST_HEAD(del_node);
}

static inline void list_replace(COM_LIST_HEAD_t *old_node,COM_LIST_HEAD_t *new_node){
    new_node->next = old_node->next;
    new_node->next->pre = new_node;
    new_node->pre = old_node->pre;
    new_node->pre->next = new_node;
}

static inline void list_empty(COM_LIST_HEAD_t *head_ptr){
    head_ptr->next = head_ptr;
}

#ifndef offsetof
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif

#define container_of(ptr, type, member) ({          \
const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
(type *)( (char *)__mptr - offsetof(type,member) );})

#define list_each(pos,head) for(pos=(head)->next;pos !=(head);pos=pos->next)
/* 遍历链表时应该使用下面的safe模式链表查找 */
#define list_each_safe(pos,n,head) for(pos=(head)->next,n=pos->next;pos !=(head);pos=n,n=pos->next)
#define list_node_get(ptr,type,member) container_of(ptr,type,member)
#endif //NEWCGI_COM_LIST_H
